package com.haipi.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.common.util.StringUtil;

public class FileUploadUtil
{

    private static final Logger logger = Logger.getLogger(FileUploadUtil.class);

    public static List<FileModel> upload(HttpServletRequest request, String fileSavePath)
    {
        List<FileModel> returnList = new ArrayList<FileModel>();
        MultipartHttpServletRequest multRequest = (MultipartHttpServletRequest) request;
        Iterator it = multRequest.getFileNames();

        while (it.hasNext())
        {
            FileModel fileModel = new FileModel();
            String key = (String) it.next();
            MultipartFile uploadfile = multRequest.getFile(key);

            String fileName = uploadfile.getOriginalFilename();
            if (null == fileName || "".equals(fileName))
            {
                continue;
            }

            String ext = fileName.substring(fileName.lastIndexOf("."));
            String savePath = fileSavePath + StringUtil.getRandomCode(12) + ext;

            File file = new File(request.getSession().getServletContext().getRealPath("/") + savePath);
            if (!file.getParentFile().exists())
            {
                file.getParentFile().mkdirs();
            }

            try
            {
                uploadfile.transferTo(file);

                fileModel.setFileName(fileName);
                fileModel.setFileType(ext);
                fileModel.setFileUrl(savePath);

                returnList.add(fileModel);
            }
            catch (IllegalStateException e)
            {
                logger.error("file upload fail",e);
            }
            catch (IOException e)
            {
                logger.error("file upload fail",e);
            }
        }

        return returnList;
    }

    public static class FileModel
    {
        private String fileName;
        private String fileUrl;
        private String fileType;

        public String getFileName()
        {
            return fileName;
        }

        public void setFileName(String fileName)
        {
            this.fileName = fileName;
        }

        public String getFileUrl()
        {
            return fileUrl;
        }

        public void setFileUrl(String fileUrl)
        {
            this.fileUrl = fileUrl;
        }

        public String getFileType()
        {
            return fileType;
        }

        public void setFileType(String fileType)
        {
            this.fileType = fileType;
        }
    }

}
